if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        res[i] = fun.call(thisp, this[i], i, this);
    }

    return res;
  };
}

String.prototype.leftPad = function (l, c) { return new Array(l - this.length + 1).join(c || ' ') + this; };

var destroyAllDialogs = function()
{
	$('ui-dialog').dialog('destroy').remove();
};
var newModalDialog = function(config)
{

	if(config.doModal != undefined)
	{
		config.modal = config.doModal;
		delete config.doModal;
	}
	
	if(config.onHide != undefined)
	{
		config.close = config.onHide;
		delete config.onHide;
	}
	
	
	if(config.id)
	{
		var dialogNode = $("<div id='" + config.id + "'></div>").appendTo($('body'));
	}
	else
	{
		var dialogNode = $("<div></div>").appendTo($('body'));
	}
	
	if(config.content)
	{
		dialogNode.html(config.content);
	}
	
	if(config.href)
	{
		dialogNode.load(config.href);
	}
	dialogNode = dialogNode.dialog(config);
	dialogNode.bind('dialogclose', function(event, ui){dialogNode.dialog('destroy').remove();});
	

};

var newModalAlert = function(config)
{	
	config.buttons = { "OK": function() { $(this).dialog("close"); if(config.execute){config.execute();}}};
	newModalDialog(config);
};

var newModalConfirm = function(config)
{	
	config.buttons = {  "OK": function() { $(this).dialog("close"); if(config.execute){config.execute();}}, "Cancel": function() { $(this).dialog("close");}};
	newModalDialog(config);
	
};

var formSubmit = function(e, config)
{
	var form = e['target']; //ie: srcElement?, target | safari: srcElement, target | firefox : target, originalTarget
	form = dijit.byId(form.id) || dojo.byId(form.id);
	if(form.validate != undefined && typeof form.validate == 'function')
	{
		form.validate();
	}
	
	if(config != undefined && config.doAjax != undefined && config.doAjax == true)
	{
		//prevent the form from actually submitting
		//alert('ajax!');
		e.preventDefault();
		
		             
		//var_dump(e);
		newModalConfirm({title: 'Are You Sure?', content: 'Are you sure you want to do that?', execute:
			function()
			{
				// submit the form in the background
				//alert(form['action']);
				dojo.io.iframe.send
				(
					{
						url: form['action'],
						form: form['id'],
						handleAs: "text",
						load: handleAjaxFormResponse,
						error: handleAjaxFormError
					}
				);
				newModalDialog({id: 'processingDialog', title: 'Processing...', content: 'Processing your request...', onHide: config.onSuccess});
			}
		});
	}
};

var handleAjaxFormResponse = function(response, request)
{
	destroyAllIframes();
	//var_dump(response);
	if(response == '')
	{
		if(dijit.byId('processingDialog'))
		{
			dijit.byId('processingDialog').hide();
		}
		return;
	}
	else
	{
		newModalAlert({title: 'Error', content: 'There was an error processing your last request.'});
	}
	response = eval('('+response+')');
	
	var form = dojo.byId(request.args.form);
	clearFormError(form);

	for (elem in response)
	{
		//var_dump(elem);
		msg = "<ul class='errors'>";
		for (err in response[elem])
		{
			msg += "<li>" + response[elem][err] + "</li>";
		}
		msg += "</ul>";
		if(dojo.byId("widget_" + elem + "_error") != null)
		{
			dojo.byId("widget_" + elem + "_error").innerHTML = msg;
		}
		
	}
	
};

var handleAjaxFormError = function(e)
{
	destroyAllIframes();
	alert('error!');
	for(index in e)
	{
		alert(index + ': ' + e[index]);
	}
};

var clearFormError = function(myForm)
{
	//alert('clearing form errors!');
	var elements = myForm.elements;
	for (var i = 0; i < elements.length; i++)
	{
		if (dojo.byId("widget_" + elements[i].name + "_error"))
		{
			dojo.byId("widget_" + elements[i].name + "_error").innerHTML = "";
		}
		else if(dojo.byId("widget_" + elements[i].name))
		{
			//alert(elements[i].name);
			div = document.createElement("div");
			div.setAttribute("id", "widget_" + elements[i].name + "_error");
			dojo.byId("widget_" + elements[i].name).parentNode.appendChild(div);
		}
	}
};
var var_dump = function(obj)
{
	alert(obj);
	for (index in obj)
	{
		alert(index + ': ' + obj[index]);
	}
};

var feedBushidoGrid = function(gridId, url)
{
	$.post
	(
		url,
		null,
		function(jsonData, status)
		{
			jsonData.page = 1;
			jsonData.total = 1;
			jsonData.records = jsonData.items.length;

			if(jsonData.items.length > 0)
			{
				$("#" + gridId)[0].addJSONData(jsonData);
				$("#" + gridId).setGridParam({datatype:'local'});
			}
		},
		'json'
	);
};
var BushidoGrid = function(config)
{
	if($("#" + config.id).length > 0)
	{
		$(config.parentNode).html('');
	}
	var gridNode = $("<TABLE class='scroll' style='height:100%;width:100%;' id='" + config.id + "'></TABLE>").appendTo(config.parentNode);
	var gridPager = $("<DIV class='scroll' id='" + config.id + "_pager'></DIV>").insertAfter(gridNode);
	var gridColNames = [];
	
	for (var i in config.structure)
	{
		if(config.structure[i].field)
		{
			config.structure[i].label = config.structure[i].name;
			config.structure[i].name = config.structure[i].field;
			delete(config.structure[i].field);
		}
	}
	var grid = gridNode.jqGrid
	(
		{
			height: "100%",
			width: "700",
			rowNum: -1,
			datatype: function(postData)
			{
				feedBushidoGrid(config.id, config.url);
			},
			colModel: config.structure,
			jsonReader:
			{
				root: "items",
				repeatitems: false,
				id: "0"
			},
			loadOnce: true,
			pager: config.id + '_pager',
			onSelectRow: config.onRowClick/*,
			
			gridComplete: function()
			{
				$('div.ui-jqgrid').each(function()
				{
					$(this).width('auto');
				});
				$('div.ui-jqgrid-view').each(function()
				{
					$(this).width('auto');
				});
				
				$('div.ui-jqgrid-hdiv').each(function()
				{
					$(this).width('auto');
				});
				$('div.ui-jqgrid-bdiv').each(function()
				{
					$(this).width('auto');
				});
				$('.ui-jqgrid, .ui-jqgrid-hbox').css('padding-right', 0);
				$('div.ui-jqgrid').children('DIV').each(function()
				{
					$(this).width('auto');
					$(this).find('TABLE').width('100%').find('TR').find('TD, TH').width('auto');
				});
			}
			*/
		}
	);
	return grid;
};
